package com.zhang.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.yygh.cmn.excel.Student;
import com.zhang.yygh.cmn.listener.DictListener;
import com.zhang.yygh.cmn.listener.ExcelListener;
import com.zhang.yygh.cmn.mapper.DictMapper;
import com.zhang.yygh.cmn.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author zhang
 * @since 2022-03-03
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //缓存的数据：①当不指定key时，存储在redis数据库中的健就是value值+参数::pid，值就是缓存的当前方法的返回结果
    //②：当在注解中指定了key,那么存储在redis中的键就是value值+key值
    @Cacheable(value = "childlist",key = "'selectIndexList'+#pid")
    @Override
    public List<Dict> getDictListByPid(Long pid) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        for (Dict dict : dicts) {
            Long dictId = dict.getId();
            boolean result=this.hasChild(dictId);
            dict.setHasChildren(result);
        }
        return dicts;
    }

    @Override
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("字典数据", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictEvoList = new ArrayList<DictEeVo>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);//将一个对象中的属性值拷贝到另一个对象的对应的属性上。
            dictEvoList.add(dictEeVo);
        }
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet().doWrite(dictEvoList);
    }

    @Override
    public void upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper))
                .sheet().doRead();
    }

    @Override
    public String getAddressNameByValue(String dicCode,Long value) {
        /*//如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if(StringUtils.isEmpty(dicCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        } else {
            Dict parentDict = this.getDictByDictCode(dicCode);
            if(null == parentDict) return "";
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id",
                    parentDict.getId()).eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        }
        return "";*/
        if (StringUtils.isEmpty(dicCode)){
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            return dict.getName();
        }else {
            QueryWrapper<Dict> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("dict_code", dicCode);
            Dict dict = baseMapper.selectOne(queryWrapper1);
            QueryWrapper<Dict> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("parent_id",dict.getId());
            queryWrapper2.eq("value",value);
            Dict result = baseMapper.selectOne(queryWrapper2);
            return result.getName();

        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        QueryWrapper<Dict> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("parent_id",dict.getId());
        return baseMapper.selectList(queryWrapper1);
    }

    /*//实现方法 根据dict_code查询
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }*/

    //判断当前元素是否有下一级元素，有就返回true，没有就返回false
    private boolean hasChild(Long pid) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count>0;
    }

}
